<template>
  <div class="device-list-container">
    <el-header class="device-list-header">
      <div class="header-content">
        <div class="header-left">
          <img src="@/assets/logo.svg" alt="Logo" class="logo">
          <h1 class="title">查看设备信息</h1>
        </div>
        <div class="header-right">
          <div class="user-info">
            <el-icon class="user-icon"><User /></el-icon>
            <span class="nickname">{{ currentUser.nickname || currentUser.username }}</span>
          </div>
          <el-button type="danger" @click="logout" size="large">退出登录</el-button>
        </div>
      </div>
    </el-header>

    <el-main class="device-list-main">
      <el-card class="device-list-card">
        <template #header>
          <div class="card-header">
            <span class="card-title">设备列表</span>
            <div class="header-buttons">
              <el-button type="primary" @click="refreshDevices">刷新数据</el-button>
              <el-button type="success" @click="openAddDialog">添加设备</el-button>
            </div>
          </div>
        </template>

        <el-table :data="currentDevices" stripe style="width: 100%" border>
          <el-table-column prop="deviceId" label="设备ID" width="140" align="center" sortable />
          <el-table-column prop="deviceName" label="设备名称" width="180" align="center" sortable />
          <el-table-column prop="deviceType" label="设备类型" width="140" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.deviceType === 1">灯光</el-tag>
              <el-tag v-else-if="scope.row.deviceType === 2">空调</el-tag>
              <el-tag v-else-if="scope.row.deviceType === 3">门锁</el-tag>
              <el-tag v-else-if="scope.row.deviceType === 4">窗帘</el-tag>
              <el-tag v-else-if="scope.row.deviceType === 5">传感器</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="deviceSn" label="设备序列号" width="160" align="center" />
          <el-table-column prop="status" label="设备状态" width="140" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.status === 1" type="success">在线</el-tag>
              <el-tag v-else type="warning">离线</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="roomId" label="房间ID" width="120" align="center" />
          <el-table-column prop="protocol" label="通信协议" width="160" align="center" />
          <el-table-column prop="createdTime" label="创建时间" width="200" align="center" sortable>
            <template #default="scope">
              {{ formatDate(scope.row.createdTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" align="center">
            <template #default="scope">
              <el-button type="primary" size="small" @click="viewDeviceDetail(scope.row.deviceId)">查看详情</el-button>
              <el-button type="warning" size="small" @click="editDevice(scope.row.deviceId)">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 添加设备对话框 -->
        <el-dialog
          v-model="addDialogVisible"
          title="添加设备"
          width="500px"
          :before-close="handleClose"
        >
          <el-form
            ref="addDeviceFormRef"
            :model="addDeviceForm"
            :rules="addDeviceRules"
            label-width="120px"
          >
            <el-form-item prop="deviceName" label="设备名称">
              <el-input v-model="addDeviceForm.deviceName" placeholder="请输入设备名称" />
            </el-form-item>

            <el-form-item prop="deviceSn" label="设备序列号">
              <el-input v-model="addDeviceForm.deviceSn" placeholder="请输入设备序列号" />
            </el-form-item>

            <el-form-item prop="deviceType" label="设备类型">
              <el-select v-model="addDeviceForm.deviceType" placeholder="请选择设备类型">
                <el-option label="灯光" value="1" />
                <el-option label="空调" value="2" />
                <el-option label="门锁" value="3" />
                <el-option label="窗帘" value="4" />
                <el-option label="传感器" value="5" />
              </el-select>
            </el-form-item>

            <el-form-item prop="roomId" label="房间ID">
              <el-input-number
                v-model="addDeviceForm.roomId"
                :min="1"
                placeholder="请输入房间ID"
              />
            </el-form-item>

            <el-form-item prop="status" label="设备状态">
              <el-select v-model="addDeviceForm.status" placeholder="请选择设备状态">
                <el-option label="在线" value="1" />
                <el-option label="离线" value="0" />
              </el-select>
            </el-form-item>

            <el-form-item prop="protocol" label="通信协议">
              <el-input v-model="addDeviceForm.protocol" placeholder="请输入通信协议" />
            </el-form-item>

            <el-form-item prop="createdTime" label="创建时间">
              <el-date-picker
                v-model="addDeviceForm.createdTime"
                type="datetime"
                placeholder="请选择创建时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-form>

          <template #footer>
            <div class="dialog-footer">
              <el-button @click="handleClose">取消</el-button>
              <el-button type="primary" @click="submitAddDevice">确认添加</el-button>
            </div>
          </template>
        </el-dialog>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalDevices"
          ></el-pagination>
        </div>
      </el-card>
    </el-main>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { User } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const router = useRouter()

const currentUser = ref({})
const allDevices = ref([])
const currentPage = ref(1)
const pageSize = ref(10)

// 添加设备对话框相关
const addDialogVisible = ref(false)
const addDeviceFormRef = ref(null)
const addDeviceForm = ref({
  deviceName: '',
  deviceSn: '',
  deviceType: '',
  roomId: null,
  status: '',
  protocol: '',
  createdTime: ''
})

// 添加设备表单验证规则
const addDeviceRules = ref({
  deviceName: [
    { required: true, message: '请输入设备名称', trigger: 'blur' },
    { min: 2, max: 50, message: '设备名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  deviceSn: [
    { required: true, message: '请输入设备序列号', trigger: 'blur' },
    { min: 6, max: 20, message: '设备序列号长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  deviceType: [
    { required: true, message: '请选择设备类型', trigger: 'change' }
  ],
  roomId: [
    { required: true, message: '请输入房间ID', trigger: 'blur' },
    { type: 'number', min: 1, message: '房间ID必须为正整数', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择设备状态', trigger: 'change' }
  ],
  protocol: [
    { required: true, message: '请输入通信协议', trigger: 'blur' },
    { min: 2, max: 20, message: '通信协议长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  createdTime: [
    { required: true, message: '请选择创建时间', trigger: 'change' }
  ]
})

// 计算属性：当前页设备数据
const currentDevices = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
    return allDevices.value.slice(start, end)
})

// 计算属性：设备总数
const totalDevices = computed(() => allDevices.value.length)

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 刷新设备列表
const refreshDevices = () => {
  loadDevices()
}

// 加载设备列表
const loadDevices = async () => {
  try {
    const res = await axios.get('/devices')
    if (res.data.code === 200) {
      allDevices.value = res.data.data
      ElMessage.success('设备列表加载成功')
    } else {
      ElMessage.error(res.data.msg || '加载设备列表失败')
      allDevices.value = []
    }
  } catch (err) {
    console.error('加载设备列表错误:', err)
    ElMessage.error('加载设备列表失败，请检查网络连接')
    allDevices.value = []
  }
}

// 查看设备详情
const viewDeviceDetail = (deviceId) => {
  router.push(`/device-detail/${deviceId}`)
}

// 编辑设备
const editDevice = (deviceId) => {
  router.push(`/edit-device/${deviceId}`)
}

// 打开添加设备对话框
const openAddDialog = () => {
  addDialogVisible.value = true
}

// 关闭添加设备对话框
const handleClose = () => {
  if (addDeviceFormRef.value) {
    addDeviceFormRef.value.resetFields()
  }
  addDialogVisible.value = false
}

// 提交添加设备表单
const submitAddDevice = async () => {
  if (!addDeviceFormRef.value) return

  try {
    // 表单验证
    await addDeviceFormRef.value.validate()

    // 调用后端接口添加设备
    const res = await axios.post('/devices', addDeviceForm.value)
    if (res.data.code === 200) {
      ElMessage.success('设备添加成功')
      // 关闭对话框
      handleClose()
      // 刷新设备列表
      refreshDevices()
    } else {
      ElMessage.error(res.data.msg || '设备添加失败')
    }
  } catch (err) {
    if (err.response) {
      // HTTP请求错误
      console.error('添加设备HTTP错误:', err.response.data)
      ElMessage.error('添加设备失败: ' + (err.response.data.msg || err.response.statusText))
    } else if (err.message) {
      // 表单验证失败
      console.error('添加设备表单验证错误:', err.message)
    } else {
      // 其他错误
      console.error('添加设备错误:', err)
      ElMessage.error('添加设备失败，请检查网络连接')
    }
  }
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  loadDevices()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadDevices()
}

// 退出登录
const logout = () => {
  localStorage.removeItem('token')
  localStorage.removeItem('user')
  router.push('/')
}

// 页面加载时初始化数据
onMounted(() => {
  const userInfo = localStorage.getItem('user')
  if (userInfo) {
    currentUser.value = JSON.parse(userInfo)
    loadDevices()
  } else {
    router.push('/')
  }
})
</script>

<style scoped>
.device-list-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f0f2f5;
}

.device-list-header {
  background-color: #ffffff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 40px;
  height: 80px;
  box-sizing: border-box;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.logo {
  width: 50px;
  height: 50px;
  object-fit: contain;
}

.title {
  color: #303133;
  font-size: 24px;
  font-weight: 600;
  margin: 0;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #606266;
  font-size: 16px;
}

.user-icon {
  font-size: 24px;
}

.nickname {
  font-weight: 500;
}

.device-list-main {
  padding: 20px 40px;
  flex: 1;
  overflow: auto;
}

.device-list-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>